package com.learn.concurrent.blockingqueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;

/**
 * @author wangxing
 * @version 2020/8/17 6:16 Administrator
 */
public class NumberConsumer implements Runnable {
    Logger logger = LoggerFactory.getLogger(NumberConsumer.class);
    private BlockingQueue<Integer> queue;
    private final int poisonPill;

    public NumberConsumer(BlockingQueue<Integer> queue, int poisonPill) {
        this.queue = queue;
        this.poisonPill = poisonPill;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try {
            while (true){
                Integer num = queue.take();
                if (num.equals(poisonPill)){
                    return;
                }
                logger.info("消费者{}获取数据,数据编号:{}",Thread.currentThread().getId(),num);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }
}
